package com.hs.hlw.credit.system.business.service.impl;

import com.hs.hlw.credit.system.business.dto.ResponseDto;
import com.hs.hlw.credit.system.business.service.DataSourceService;
import com.hs.hlw.credit.system.business.service.TableService;
import com.hs.hlw.credit.system.data.mybatis.Pageable;
import com.hs.hlw.credit.system.data.primary.mapper.DataSourceMapper;
import com.hs.hlw.credit.system.data.primary.model.DataSource;
import com.hs.hlw.credit.system.data.secondary.mapper.TableFileMapper;
import com.hs.hlw.credit.system.data.secondary.model.TableFile;
import com.hualongdata.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TableServiceImpl
 * @author zhb
 * @date 2018/11/19
 */
@Service
public class TableServiceImpl implements TableService {
    private @Autowired DataSourceMapper dataSourceMapper;
    private @Autowired TableFileMapper tableFileMapper;

    /**
     * 分页查询
     * @param pageable
     * @return
     */
    public ResponseDto page(Pageable pageable) {
        Integer dataSourceId = (Integer) pageable.getParams().get("dataSourceId");
        if (dataSourceId != null) {
            DataSource dataSource = dataSourceMapper.selectByPrimaryKey(dataSourceId);
            if (dataSource == null) {
                throw new BusinessException("数据源不存在");
            } else {
                pageable.addParam("dbName", dataSource.getEnglishName());
            }
        }

        // 获取数据
        List<TableFile> list = tableFileMapper.page(pageable);
        List<Map<String, Object>> _list = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (TableFile dto : list) {
                Map<String, Object> map = new HashMap<>();
                _list.add(map);
                map.put("id", dto.getXmlid());
                map.put("name", dto.getDatacnname());
                map.put("code", dto.getDataname());
            }
        }

        return new ResponseDto("查询成功", pageable, _list);
    }
}